<template>
  <div class="page device-page">
    <div class="page-title-box card-wrapper">
      <span class="page-title-text">申请流程管理</span>
      <div class="page-title-options">
        <a-button type="primary" @click="handlePopCreateModal">添加流程</a-button>
      </div>
    </div>
    <div class="page-list-content card-wrapper">
      <a-table :data-source="tableData" :columns="columns" :pagination="false">
        <template #bodyCell="{record, column}">
          <template v-if="column.dataIndex === 'needApply'">
            <span v-if="record.needApply === BoolStatus.Y">需要</span>
            <span v-if="record.needApply === BoolStatus.N">不需要</span>
          </template>
          <template v-if="column.dataIndex === 'status'">
            <span v-if="record.status === ApplyCategoryStatus.Normal">正常</span>
            <span class="status-text-delete" v-if="record.status === ApplyCategoryStatus.Deleted">已删除</span>
          </template>
          <template v-if="column.dataIndex === 'option'">
            <a-button type="link" @click="handlePopEditModal(record)" v-if="record.status !== ApplyCategoryStatus.Deleted">编辑</a-button>
            <a-button type="link" danger v-if="record.status === ApplyCategoryStatus.Normal" @click="setApplyCategoryStatus(record, ApplyCategoryStatus.Deleted)">删除</a-button>
            <a-button type="link" v-if="record.status === ApplyCategoryStatus.Deleted" @click="setApplyCategoryStatus(record, ApplyCategoryStatus.Normal)">恢复</a-button>
          </template>
        </template>
      </a-table>
      <a-modal v-model:visible="modalVisible" width="40%" :title="editFlag ? '编辑流程' : '添加流程'" :footer="null">
        <a-form
            ref="formRef"
            :model="formState"
            name="basic"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 16 }"
            autocomplete="off"
            @finish="onFinish">
          <a-form-item
              label="名称"
              name="name"
              :rules="[{ required: true, trigger: 'blur', message: '名称必填' }]">
            <a-input v-model:value="formState.name" />
          </a-form-item>
          <a-form-item
              label="需要审核"
              name="needApply">
            <a-radio-group v-model:value="formState.needApply">
              <a-radio :value="BoolStatus.Y">需要</a-radio>
              <a-radio :value="BoolStatus.N">不需要</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item
              label="审核人员"
              name="approveAccountIdArr">
            <a-select :disabled="!formState.needApply" mode="multiple" v-model:value="formState.approveAccountIdArr" :options="personList"></a-select>
          </a-form-item>
          <a-form-item
              label="状态"
              name="status">
            <a-select disabled allow-clear v-model:value="formState.status" >
              <a-select-option :value="ApplyCategoryStatus.Normal" >正常</a-select-option>
              <a-select-option :value="ApplyCategoryStatus.Deleted" >已删除</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
            <div class="btn-row">
              <a-button @click="modalVisible = false">取消</a-button>
              <a-button type="primary" html-type="submit">保存</a-button>
            </div>
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
  </div>
</template>

<script setup lang="ts">
import {nextTick, onMounted, ref} from 'vue'
import {
  ApplyCategoryItem,
  ApplyCategoryStatus,
  BoolStatus,
  OptionItem,
  PersonItem,
  PersonStatus,
  ResDto
} from "../../types/common";
import applyCategoryApi from '../../api/apply-category/index';
import personApi from '../../api/person/index';
import {message} from "ant-design-vue";

const modalVisible = ref(false)
const editFlag = ref(false)
const formRef = ref()
const formState = ref<ApplyCategoryItem>({
  id: '',
  name: '',
  needApply: BoolStatus.Y,
  approveAccountIds: '',
  approveAccountIdArr: [],
  status: ApplyCategoryStatus.Normal
})
const tableData = ref<ApplyCategoryItem[]>([])
const columns = [
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
  },{
    title: '需要审核',
    dataIndex: 'needApply',
    key: 'needApply',
  },{
    title: '审核人员',
    dataIndex: 'approvePersonNames',
    key: 'approvePersonNames',
  },{
    title: '状态',
    dataIndex: 'status',
    key: 'status',
  },{
    title: '操作',
    dataIndex: 'option',
    key: 'option',
  },

]
const personCacheObj: {[key: string]: PersonItem} = {}
const personList = ref<OptionItem[]>([])
const getPersonList = async () => {
  try {
    const res = await personApi.getList(PersonStatus.Normal)
    if (res.data && res.data.length) {
      res.data.forEach((p: PersonItem) => {
        personList.value.push({
          label: p.name,
          value: p.accountId,
          disabled: p.status !== PersonStatus.Normal,
        })
        personCacheObj[p.accountId] = p
      })
    }
  } catch(e){

  }
}
const getApplyCategoryList = () => {
  applyCategoryApi.getList().then((res: ResDto) => {
    if (res.data && res.data.length) {
      res.data.forEach((d: ApplyCategoryItem) => {
        d.approvePersonNames = ''
        d.approveAccountIdArr = []
        if (d.approveAccountIds) {
          const approve: string[] = []
          const accountIdArr = d.approveAccountIds.split(',')
          d.approveAccountIdArr = accountIdArr
          accountIdArr.forEach((accId: string) => {
            if (accId && personCacheObj[accId]) {
              approve.push(personCacheObj[accId].name)
            }
          })
          d.approvePersonNames = approve.join(',')
        }
      })
      tableData.value = res.data
    }
  })
}
onMounted(async () => {
  await getPersonList()
  getApplyCategoryList()
})
const setApplyCategoryStatus = (record: ApplyCategoryItem, status: ApplyCategoryStatus) => {
  applyCategoryApi.edit({...record, status}).then((res: ResDto) => {
    if (res.code === 0) {
      message.success('操作成功')
      getApplyCategoryList()
    } else {
      message.error(res.message)
    }
  }).catch((e: any) => {
    console.log(e)
    message.error('服务异常')
  })
}

const handlePopEditModal = (record: ApplyCategoryItem) => {
  editFlag.value = true
  formState.value = JSON.parse(JSON.stringify(record))
  formState.value.approveAccountIdArr = formState.value.approveAccountIds ? formState.value.approveAccountIds.split(',') : []
  modalVisible.value = true
  nextTick(() => {
    formRef.value.clearValidate()
  })
}
const handlePopCreateModal = () => {
  editFlag.value = false
  formState.value = {
    id: '',
    name: '',
    needApply: BoolStatus.Y,
    approveAccountIds: '',
    approveAccountIdArr: [],
    status: ApplyCategoryStatus.Normal
  }
  modalVisible.value = true
  nextTick(() => {
    formRef.value.clearValidate()
  })
}
const onFinish = () => {
  const params = JSON.parse(JSON.stringify(formState.value))
  if (!params.needApply) {
    params.approveAccountIds = ''
  } else {
    if (!params.approveAccountIdArr || !params.approveAccountIdArr.length) {
      message.error('请至少选择一个审核人员')
      return
    }
    params.approveAccountIds = params.approveAccountIdArr.join(',')
  }
  let p
  if (editFlag.value) {
    p = applyCategoryApi.edit(params)
  } else {
    p = applyCategoryApi.add(params)
  }
  p.then((res) => {
    if (res.code === 0) {
      message.success('保存成功')
      modalVisible.value = false
      getApplyCategoryList()
    } else {
      message.error(res.message)
    }
  }).catch((e: any) => {
    message.error('服务异常')
  })
}
</script>

<style scoped>

</style>
